import React, { useEffect, useState } from 'react';
import { Layout } from 'antd';
import { IFile } from '@/ts/core';
import { Resizable } from 'devextreme-react';
import useStorage from '@/hooks/useStorage';
const { Content, Sider } = Layout;
import TargetActivity from '.';
import { ITarget } from './../../ts/core/target/base/target';
import useTimeoutHanlder from '@/hooks/useTimeoutHanlder';
import DirectoryViewer from '@/components/Directory/views';

interface ActivityProps {
  target: ITarget;
}

/** 内部机构列表的动态 */
const TargetsActivity: React.FC<ActivityProps> = ({ target }) => {
  const [mainWidth, setMainWidth] = useStorage<string | number>('main2Width', '40%');
  const [current, setCurrent] = useState<ITarget | 'disk'>('disk');
  const [submitHanlder, clearHanlder] = useTimeoutHanlder();
  const [currentTag, setCurrentTag] = useState('全部');
  const [focusFile, setFocusFile] = useState<IFile>();
  const [content, setContent] = useState<IFile[]>([]);

  useEffect(() => {
    if (target) {
      setCurrentTag('全部');
      if (current === 'disk') {
        const newTasks = target.content();
        setContent(newTasks);
        if (newTasks.length > 0) setFocusFile(newTasks[0]);
      } else {
        current.subscribe(() => {
          setContent(current.content());
        });
      }
    }
  }, [target]);
  const clickHanlder = (file: ITarget | undefined, dblclick: boolean) => {
    if (dblclick) {
      clearHanlder();
      if (file) setCurrent(file);
    } else {
      submitHanlder(() => focusHanlder(file), 300);
    }
  };
  const focusHanlder = (file: IFile | undefined) => {
    if (file && file.key !== focusFile?.key) setFocusFile(file);
  };
  return (
    <Layout className={'main_layout'}>
      <Layout className={'body'}>
        <Resizable
          handles={'right'}
          width={mainWidth}
          onResize={(e) => setMainWidth(e.width)}>
          <Sider className={'content'} width={'100%'}>
            <DirectoryViewer
              isMenu
              initTags={['全部']}
              selectFiles={[]}
              extraTags={true}
              focusFile={focusFile}
              content={content}
              currentTag={currentTag}
              tagChanged={(t) => setCurrentTag(t)}
              fileOpen={(entity, dblclick) => clickHanlder(entity as ITarget, dblclick)}
              contextMenu={(_entity) => {
                return {
                  items: [],
                };
              }}
            />
          </Sider>
        </Resizable>
        <Content className={'content'}>
          {focusFile && (
            <TargetActivity
              height={'100%'}
              activity={(focusFile as ITarget).session.activity}
            />
          )}
        </Content>
      </Layout>
    </Layout>
  );
};

export default TargetsActivity;
